<template>
  <!-- 优惠券 -->
    <zsearch v-loading="loading">
      <template #title>
          <span>优惠券</span>
      </template>
      <template #btns>
        <!-- <el-button class="btn-1" @click="hanledSearch" v-jurisdiction="'pay:coupons:getIssueCouponsModel'">查询</el-button> -->
			  <el-button class="btn-2" @click="openCoupon" v-jurisdiction="'pay:coupons:createCustomerCouponsModel'">添加优惠券</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          :header-cell-style="{background:'#11b9d0', color:'#fff'}"
          :height="'100%'"
        ></ztable>
      </template>
      <template #page>
        <!-- <zpage
            :currentPage="current" 
            :total="total" 
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage> -->
      </template>
    </zsearch>

    <zdialog title="添加优惠券" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <div class="leftToRight-layout">
            <div class="label">
              <span>标题</span>
            </div>
            <div class="operations">
              <el-input v-model="title"></el-input>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>内容</span>
            </div>
            <div class="operations">
              <el-input v-model="content"></el-input>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>时间类型</span>
            </div>
            <div class="operations">
              <el-select v-model="timeType"  placeholder="请选择">
                <el-option
                  v-for="item in timeTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div v-if="timeType === '按日期计算'" class="leftToRight-layout">
            <div class="label">
              <span>区域</span>
            </div>
            <div class="operations">
              <el-date-picker
                v-model="Time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </div>
          </div>
          <div v-if="timeType === '按发放时间计算'" class="leftToRight-layout">
            <div class="label">
              <span>区域</span>
            </div>
            <div class="operations">
              <div class="f-a">
                <el-input placeholder="请输入发放时间"  v-model="startTimeDay"></el-input>~
                <el-input placeholder="请输入" v-model="endTimeDay"></el-input>
              </div>
            </div>
          </div>

          <div class="leftToRight-layout">
            <div class="label">
              <span>是否启用</span>
            </div>
            <div class="operations">
              <el-select v-model="showStatus"  placeholder="请选择">
                <el-option
                  v-for="item in showStatusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>类型</span>
            </div>
            <div class="operations">
              <el-select v-model="type"  placeholder="请选择">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>逻辑类型</span>
            </div>
            <div class="operations">
              <el-select v-model="ruleType"  placeholder="请选择">
                <el-option
                  v-for="item in ruleTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>

          <component :is="showWidget(item.type)" v-for="item in ruleTypeDataList" :key="item.name" :struc="item" :passWidth="50" />
        </div>
			</template>
    </zdialog>
</template>

<script lang='ts'>
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'

import useConfgin from './../../../hook/getconfig'
import useShowWidget from "./../../../components/widget/usechoose";
import useRequet, { RespData } from "./../../../hook/network"
import { ElMessage } from 'element-plus'



import { defineComponent, reactive, toRefs, ref, watch } from 'vue'

type Options = {
  id: string | number,
  name: string | number
}
const configID = 545;
export default defineComponent({
  name: 'Manage',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog
  },
  setup() {
    const showWidget = useShowWidget;
    const rowList = useConfgin(configID)
    console.log('优惠券', rowList)
    // 空白字符
    const emsp = '\u2003\u2003'
    const groupData  = rowList.groupDataList.value;
    const request = useRequet({ path: "" });
    let search = reactive({
      name: '',

      loading: false,

      current: 1,
      size: 10,
      total: 0,

      timeTypeOptions:[] as Options[],
      Time:[],
      showStatusOptions: [
        {
          id: 0,
          name: "否"
        },
        {
          id: 1,
          name: "是"
        }
      ],
      typeOptions: [] as Options[],
      ruleTypeOptions: [] as Options[],
      ruleTypeDataList: [] as any,
      isClick: false,
    })
    let addCoupon = reactive({
      title: '',
      content: '',
      timeType: '按日期计算',
      startTime: '',
      endTime: '',
      startTimeDay: '',
      endTimeDay: '',
      showStatus: 1,
      type: '',
      ruleType:'',
      other: {} as any
    })
    const data = ref([])
    
    watch(() => addCoupon.ruleType, (type, prevType) => {
      if(type) {
        getRuleTypeData(type)
      }
      
    })
    //搜索
    const hanledSearch = () => {
      req()
    }
    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
		}

    

    const req = () => {
      search.loading = true
      request.sendRequest({
        address: 'pay/coupons/getIssueCouponsModel',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
					data.value = resp.data
          // search.total = resp.data.total
          // search.current = resp.data.current

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    req()

    // 获取时间类型 
    const getType = () => {

      request.sendRequest({
        address: 'pay/coupons/getCouponsTypeList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          search.typeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })

      request.sendRequest({
        address: 'pay/coupons/getCouponsTimeTypeList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          search.timeTypeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })

      // 获取逻辑类型
      request.sendRequest({
        address: 'pay/coupons/getCouponsTypeSelect',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          search.ruleTypeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    // 得到逻辑类型的数据
    const getRuleTypeData = (type: string) => {
      request.sendRequest({
        address: 'pay/coupons/getCouponsTypeOption',
        params: {
          ruleType: type
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          search.ruleTypeDataList = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const closeDialog = () => {
      dialogVisible.value = false
      reset()
    }
    const reset = () => {
      addCoupon.title = ''
      addCoupon.content = ''
      addCoupon.other = {}
      addCoupon.timeType = '按日期计算'
      addCoupon.startTime = ''
      addCoupon.endTime = ''
      addCoupon.startTimeDay = ''
      addCoupon.endTimeDay = ''
      addCoupon.showStatus = 1
      addCoupon.type = ''
      addCoupon.ruleType =''
      search.ruleTypeDataList = []
      search.Time = []
    }

    const dialogVisible = ref(false)

    const openCoupon = () => {
      getType()
      dialogVisible.value = true
    }

    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
          reset()
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
          if(search.Time.length > 0) {
            addCoupon.startTime = search.Time[0]
            addCoupon.endTime = search.Time[1]
          }
          search.ruleTypeDataList.forEach( (item:any) => {
            addCoupon.other[item.name] = item.value
          })
          
          if(!addCoupon.title) {
            ElMessage.warning('请输入标题')
            return
          }
          if(!addCoupon.content) {
            ElMessage.warning('请输入内容')
            return
          }
          if(!addCoupon.type) {
            ElMessage.warning('请选择类型')
            return
          }
          if(!addCoupon.ruleType) {
            ElMessage.warning('请选择逻辑类型')
            return
          }

          if(!search.isClick) {
            request.sendRequest({
              address: 'pay/coupons/createCustomerCouponsModel',
              params: addCoupon,
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                ElMessage.success('添加'+ resp.msg)
                search.isClick = true
                closeDialog()
                req()
                
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                search.isClick = true
              },
              method: "POST",
            })
          }
          
				}
      }
    ]

    
    return { 
      data, 
      groupData, 
      ...toRefs(search),
      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      ...toRefs(addCoupon),


      request,

      dialogVisible,
      openCoupon,
      closeDialog,
      dialogBtnData,
      showWidget,

      emsp,
    }
  }
})
</script>

<style lang="scss" scoped>
.f-d {
  display: flex;
  align-items: center;
  .input-1 {
    padding-right: 10px;
  }
}

.leftToRight-layout {
  width: 50%;
}


.f-a {
  display: flex;
  align-items: center
}
</style>